package cos.android.tim.viewythread;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class PlaygroundView extends SurfaceView implements
		SurfaceHolder.Callback {

	//private Context mContext;
	private TextView fpsTextView;
	private RelativeLayout layout;
	private int level;
	private int world;
	private PlaygroundThread platformThread;
	SurfaceHolder holder;
	Context context;

	public PlaygroundView(Context context, AttributeSet attrs) {
		super(context, attrs);

		this.context = context;
		holder = getHolder();
		holder.addCallback(this);
		setFocusable(true); // make sure we get key events

	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int width,
			int height) {
		System.out.println("Por aqui");
		platformThread.setSurfaceSize(width, height);

	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {

		platformThread = new PlaygroundThread(holder, context, new Handler() {
			@Override
			public void handleMessage(Message m) {

				Long fps = m.getData().getLong("fps");

				fpsTextView.setVisibility(View.VISIBLE);
				fpsTextView.setText(fps.toString());
			}
		}, level, world);

		platformThread.setRunning(true);
		platformThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		platformThread.setRunning(false);

		while (retry) {
			try {
				platformThread.join();
				retry = false;
			} catch (InterruptedException e) {
			}
		}
	}

	public PlaygroundThread getPlatformThread() {
		return platformThread;
	}

	public void setPlatformThread(PlaygroundThread platformThread) {
		this.platformThread = platformThread;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return platformThread.doTouchEvent(event);
	}

	public TextView getFpsTextView() {
		return fpsTextView;
	}

	public void setFpsTextView(TextView fpsTextView) {
		this.fpsTextView = fpsTextView;
	}

	public RelativeLayout getLayout() {
		return layout;
	}

	public void setLayout(RelativeLayout layout) {
		this.layout = layout;
	}

	public void setLevel(int level) {
		this.level = level;
	}

	public int getLevel() {
		return level;
	}

	public int getWorld() {
		return world;
	}

	public void setWorld(int world) {
		this.world = world;
	}
	
	public void reset(){
		platformThread.reset();
	}

}
